package com.boboPlanet.user.lock;

import com.boboPlanet.user.lock.impl.DistributedMySqlLock;
import com.boboPlanet.user.lock.impl.DistributedRedisLock;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistrarBeanPostProcessor;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Description: TODO 分布式锁工厂
 * @Author: mis_wu
 * @Date: 2023/3/8
 **/
@Component
public class DistributedLockFactory {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //TODO: 默认是单例的,所以每个线程 uuid 是唯一的,所以在此生成uuid,不在锁中生成
    private final String uuid;

    public DistributedLockFactory(){
        this.uuid = UUID.randomUUID().toString();
    }

    /**
     * redis分布式锁
     * @param lockName String
     * @return DistributedRedisLock
     */
    public DistributedRedisLock getRedisLock(String lockName){
        return new DistributedRedisLock(stringRedisTemplate,lockName,uuid);
    }

    /**
     * redis 分布式锁
     * @param lockName lockName
     * @return DistributedRedisLock
     * todo: DistributedRedisLock 替换为 Mysql 的锁
     */
    public DistributedMySqlLock getMysqlLock(String lockName){
        return new DistributedMySqlLock(lockName,uuid);
    }

    public ErrorPageRegistrar errorPageRegistrar(){
        return new ErrorPageRegistrar() {
            @Override
            public void registerErrorPages(ErrorPageRegistry registry) {
                registry.addErrorPages(new ErrorPage("/error"));
            }
        };
    }
    public ErrorPageRegistrarBeanPostProcessor errorPageRegistrarBeanPostProcessor(){
        return new ErrorPageRegistrarBeanPostProcessor();
    }

}
